package pl.edu.mimuw.mas.agent;

import java.util.ArrayList;
import java.util.List;

import pl.edu.mimuw.mas.agent.behaviour.DFRegisterBehaviour;
import pl.edu.mimuw.mas.agent.behaviour.deer.DestinationBehaviour;
import pl.edu.mimuw.mas.agent.behaviour.deer.FleeServerBehaviour;
import pl.edu.mimuw.mas.agent.behaviour.deer.MoveBehaviour;
import pl.edu.mimuw.mas.agent.behaviour.deer.ShootServerBahaviour;
import pl.edu.mimuw.mas.chart.Chart;
import pl.edu.mimuw.mas.util.AgentColor;
import pl.edu.mimuw.mas.util.FearSource;
import pl.edu.mimuw.mas.util.Position;
import pl.edu.mimuw.mas.util.PositionHelper;

public class DeerAgent extends AbstractAgent {

	private static final long serialVersionUID = -4917941629692761791L;

	public static final String SERVICE_TYPE = "deer-service";
	
	public static final String SHOOT_CONV = "shoot-conv";
	public static final String SCARE_CONV = "scare-conv";
	
	private Position dest = new Position();
	
	private List<FearSource> fearSources = new ArrayList<FearSource>(); 
	
	public Position getDest() {
		return dest;
	}

	protected void setup() {
		if (!setServiceAgents()) {
			doDelete();
			return;
		}
		
		setLanguages();
		
		try {
			Object[] obj = getArguments();
			chart = (Chart) obj[0];						
		} catch (Exception e) {
			logger.error("{}: Błąd podczas inicjalizacji", getName(), e);
			doDelete();
			return;
		}

		position = PositionHelper.getRandomPosition(this);

		r = AgentColor.DEER_COLOR[0];
		g = AgentColor.DEER_COLOR[1];
		b = AgentColor.DEER_COLOR[2];

		addBehaviour(new DFRegisterBehaviour(this, SERVICE_TYPE));
		addBehaviour(new MoveBehaviour(this));
		addBehaviour(new DestinationBehaviour(this));
		addBehaviour(new ShootServerBahaviour(this));
		addBehaviour(new FleeServerBehaviour(this));
	}
	
	public void addFearSource(Position p, long t) {
		if (fearSources.size() == 0) {
			logger.info("{} : rozpoczynam ucieczkę!", getName());
		}
		fearSources.add(new FearSource(p, t));
	}
	
	public List<FearSource> getFearSources() {
		return fearSources;
	}
	
	public void organizeFearSources() {
		List<FearSource> newFearSources = new ArrayList<FearSource>();
		
		long currTime = System.currentTimeMillis();
		for (FearSource fs : fearSources) {
			if (fs.timeout >= currTime) {
				newFearSources.add(fs);
			}
		}
		
		if (newFearSources.size() == 0 && fearSources.size() != 0) {
			logger.info("{} : koncze ucieczkę!", getName());
		}
		
		fearSources = newFearSources;
	}
	
}

